<!--/**
* @author xuyh0817
* @email xuyh0817@foxmail.com
* @date 2022-02-16 15:58
* @version 2.0.0
* @doc todo
* @website todo
* @remark  如果要分发源码，需在本文件顶部保留此文件头信息！！
*/
-->
<template>
  <a-tree-select
    style="width: 100%"
    :value="currentValue"
    v-bind="attrs"
    :tree-data-dimple-mode="true"
    tree-node-filter-prop="title"
    :tree-data="currentTreeData"
    @change="changeHandler"
  />
</template>

<script>

import ComponentMixin from '../../XRenderMixins/XRenderComponentMixin'
import {COMPONENT_TYPE, CUSTOM_EVENT_TYPE} from '../../constants'

export default {
  name: COMPONENT_TYPE.TREE_SELECT,
  mixins: [ComponentMixin],
  props: {
    value: {
      type: [String, Array]
    }
  },
  data() {
    return {
      treeNode: []
    }
  },
  computed: {
    currentValue: {
      get() {
        const value = this.value
        const {multiple} = this.attrs
        if (multiple) {
          if (typeof (value) !== 'string' && !(value instanceof Array)) {
            console.warn(`${this.formItem.prop} value类型错误,非String或Array`)
            return []
          }

          if (value instanceof Array) {
            return value || []
          }
          return value.split(',')
        }
        return value
      }
    },
    currentTreeData: {
      get() {
        const {attrs, isDebug} = this
        const {treeData} = attrs
        if (typeof (treeData) !== 'string' && !(treeData instanceof Array)) {
          isDebug ? console.warn(`${this.formItem.prop} treeData类型错误,非String或Array`) : ''
          return []
        }
        if (treeData instanceof Array) {
          return treeData || []
        }
        return (new Function('return ' + treeData))()
      }
    }
  },
  watch: {
    currentTreeData: {
      immediate: true,
      deep: true,
      handler(data) {
        for (const obj of data) {
          this.treeData2TreeNode(obj)
        }
      }
    }
  },
  methods: {
    treeData2TreeNode(treeNode) {
      const {children, key} = treeNode
      // 复制原来的值
      if (key) {
        treeNode['originalKey'] = key
      }
      // 新的唯一值
      treeNode['key'] = Math.random().toString(36).substring(2)
      this.treeNode.push(treeNode)
      if (children) {
        for (const child of children) {
          this.treeData2TreeNode(child)
        }
      }
    },
    changeHandler(value) {
      const {formItem, attrs, isDebug, treeNode: options} = this
      const obj = {}
      // 关联的key
      let {associations} = attrs
      const {multiple} = attrs

      if (typeof (associations) !== 'string' && !(associations instanceof Array)) {
        isDebug ? console.warn(`${formItem.prop} associations类型错误,非String或Array`) : ''
        associations = []
      }
      if (typeof (associations) === 'string') {
        associations = (new Function('return ' + associations))()
      }
      if (associations instanceof Array) {
        associations = associations || []
      }

      if (!multiple) {
        value = [value]
      }
      for (const val of value) {
        // 关联的key
        for (const option of options) {
          if (option.value === val) {
            for (const association of associations) {
              if (!!association.key && !!association.mapKey) {
                obj[association.key] = option[association.mapKey]
              }
            }
          }
        }
      }

      this.$emit(CUSTOM_EVENT_TYPE.CUSTOM_EVENT, {
        type: CUSTOM_EVENT_TYPE.ASSOCIATION_CHANGE_EVENT,
        compType: COMPONENT_TYPE.CASCADER,
        prop: formItem ? formItem.prop : '',
        value: obj,
        attrs,
        formItem
      })

      const valueStr = value.join(multiple ? ',' : '')
      this.$emit(CUSTOM_EVENT_TYPE.CHANGE, {
        type: COMPONENT_TYPE.TREE_SELECT,
        prop: formItem ? formItem.prop : '',
        value: valueStr,
        attrs,
        formItem
      })
    }
  }
}
</script>

<style scoped>

</style>
